const { Server } = require("socket.io");
// 引入jwt 模块
const jwt = require("../uilt/JWT");

// 定义函数来处理数据
function socketServer(httpServer) {
  const io = new Server(httpServer);
  io.on("connection", async (socket) => {
    // 拿到token值
    let token = socket.handshake.query.token;
    let payload = jwt.verify(token);
    if (payload) {
      // 如果 token 没过期就走这
      socket.user = payload.username;
      socket.emit(msgType.chatGroup, chatData(`欢迎${socket.user}`, "广播"));
    } else {
      // token  过期了就之间senderror之间跳转回去
      socket.emit(msgType.chatError, chatData("token过期"));
    }
    // 当获取列表传来的时候
    socket.on(msgType.chatList, (msg) => {
      // 就给前端返回列表
      sendAll(io);
    });
    // 当客户端发来群发
    socket.on(msgType.chatGroup, (msg) => {
      socket.broadcast.emit(msgType.chatGroup, chatData(msg.data, socket.user));
    });
    // 当客户端发来私聊
    socket.on(msgType.singleChat, (msg) => {
      Array.from(io.sockets.sockets).forEach((item) => {
        if (item[1].user === msg.user) {
          item[1].emit(msgType.singleChat, chatData(msg.data, socket.user));
        }
      });
    });
    // 当客户端关闭的时候会发生的 事情
    socket.on("disconnect", () => {
      sendAll(io);
    });
  });
}
// 把模块暴露出去
module.exports = socketServer;
// 定义回传的数据
function chatData(data, user) {
  return {
    data,
    user,
  };
}
//定义回传类型
const msgType = {
  chatError: 0,
  chatList: 1,
  chatGroup: 2,
  singleChat: 3,
};
// 发送列表
function sendAll(io) {
  // 获取到列表;
  let arr = Array.from(io.sockets.sockets)
    .map((item) => item[1].user)
    .filter((item) => item);
  io.emit(msgType.chatList, Array.from(new Set(arr)));
}
